/**
 * @file  数据中转站
 * @author  hj
 */
// 引入数据请求API
import {APIS} from 'configPort';

var nativeApi = require('nativeApi');
import Router from 'vue-router';

/* 加载页面 */
import Vue from 'vue';
import cart from './vue/cart.vue';

Vue.use(Router);

var router = new Router();
router.map({
  '/': {
    component: cart
  }
});

export default {
  state: {
    bannerData: [],
    dictionary: {},
    isNewCount: {},
    loginData: {
      username: 'admin',
      password: '111111'
    },
    detail: {},
    menuList: [],
    show: true,
    count: 0,
    cartList: [],
    isCheckAll: false,
    settlement: 0,
    settlementurl: 'false',
    settlementData: [],
    address: {},
    goodsList: [],
    addressId: -1,
    cartsPage: 10,
    cartsNo: 1,
    scrolls: {
      scroll: {}
    },
    paramsData: ''
  },
  login: function () {
    var self = this;
    nativeApi.initAjax({
      'type': 'get',
      'url': APIS.login,
      'param': self.state.loginData,
      callback: function (result) {
        if (result && result.code === 200) {
          localStorage.setItem('login_info_test', JSON.stringify(result.data));
          router.go('/staffMenu');
        } else {
          mui.alert('登录失败' || result.msg, '提示');
        }
      }
    });
  },
  logout: function () {
    var self = this;
    nativeApi.initAjax({
      'type': 'get',
      'url': APIS.logout,
      'param': '',
      callback: function (result) {
        if (result && result.code === 200) {
          localStorage.removeItem('login_info');
          self.state.show = true;
        }
      }
    });
  },
  getcurrentuserinfo: function () {
    nativeApi.initAjax({
      'type': 'get',
      'url': APIS.getcurrentuserinfo,
      'param': '',
      callback: function (result) {
        if (result && result.code === 200) {
          localStorage.setItem('login_info_test', JSON.stringify(result.data));
        } else {
          mui.alert('请登录');
        }
      }
    });
  },
  getCarts: function () {
    var self = this;
    nativeApi.initAjax({
      type: 'get',
      url: APIS.Carts,
      data: {
        'cartsType': 'carousel_image'
      },
      callback: function (result) {
        if (result && result.code === 200) {
          self.state.count = result.data.total;
        }
      }
    });
  },
  /* 翻页相关*/
  setScroll: function (scroll) {
    this.state.scrolls.scroll = scroll;
  },
  getCartList: function () {
    var self = this;
    nativeApi.initAjax({
      type: 'get',
      url: APIS.CartList,
      param: {
        pageSize: self.state.cartsPage,
        pageNo: self.state.cartsNo
      },
      callback: function (result) {
        var endPullupToRefresh = false;
        if (result && result.code === 200) {
          var list = result.data;
          for (let i = 0; i < list.length; i++) {
            var items = list[i].items;
            list[i]['active'] = false;
            for (let j = 0; j < items.length; j++) {
              list[i].items[j]['active'] = false;
            }
            self.state.cartList.push(list[i]);
          }
          if (result.data.length < self.state.cartsPage) {
            if (result.totalSize !== '') {
              endPullupToRefresh = true;
            }
          }
          if (result.data.length > 0) {
            self.state.cartsNo = self.state.cartsNo + 1;
          }
        } else {
          endPullupToRefresh = true;
        }
        if (result.totalSize === '') {
          self.state.scrolls.scroll.disablePullupToRefresh();
        }
        self.state.scrolls.scroll.endPullupToRefresh(endPullupToRefresh);
      }
    });
  },
  getCartListUP: function () {
    var self = this;
    nativeApi.initAjax({
      type: 'get',
      url: APIS.CartList,
      param: {
        pageSize: self.state.cartsPage,
        pageNo: self.state.cartsNo
      },
      callback: function (result) {
        var endPullupToRefresh = false;
        if (result && result.code === 200) {
          var list = result.data;
          for (let i = 0; i < list.length; i++) {
            var items = list[i].items;
            list[i]['active'] = false;
            for (let j = 0; j < items.length; j++) {
              list[i].items[j]['active'] = false;
            }
            self.state.cartList.unshift(list[i]);
          }
          if (result.data.length < self.state.cartsPage) {
            endPullupToRefresh = true;
          }
          if (result.data.length > 0) {
            self.state.cartsNo = self.state.cartsNo + 1;
          }
        } else {
          endPullupToRefresh = true;
        }
        self.state.scrolls.scroll.endPulldownToRefresh(endPullupToRefresh);
      }
    });
  },
  getDictionary: function () {
    var self = this;
    nativeApi.initAjax({
      type: 'get',
      url: APIS.Dictionary,
      param: {
        'dicKey': 'hot_recommend'
      },
      callback: function (result) {
        if (result && result.code === 200) {
          self.state.dictionary = result.data;
        }
      }
    });
  },
  getIsNewCount: function () {
    var self = this;
    nativeApi.initAjax({
      type: 'get',
      url: APIS.IsNewCount,
      callback: function (result) {
        if (result && result.code === 200) {
          self.state.count = result.data.count;
        }
      }
    });
  },
  changeNum: function (goodsId, goodsNum, row, index) {
    var self = this;
    nativeApi.initAjax({
      type: 'PUT',
      url: APIS.ChangeCartGoodsNum + goodsId + '?goodsNum=' + goodsNum,
      callback: function (result) {
        if (result && result.code === 200) {
          var items = self.state.cartList[row].items;
          items[index].goodsNum = goodsNum;
          self.state.cartList[row].items = items;
          self.subtotal();
        }
      }
    });
  },
  addGoodsNum: function (row, index) {
    var self = this;
    var item = self.state.cartList[row].items[index];
    var goodsNum = parseInt(item.goodsNum) + 1;
    nativeApi.initAjax({
      type: 'PUT',
      url: APIS.ChangeCartGoodsNum + item.id + '?goodsNum=' + goodsNum,
      callback: function (result) {
        if (result && result.code === 200) {
          var items = self.state.cartList[row].items;
          items[index].goodsNum = goodsNum;
          self.state.cartList[row].items = items;
          self.subtotal();
        }
      }
    });
  },
  subGoodsNum: function (row, index) {
    var self = this;
    var item = self.state.cartList[row].items[index];
    var goodsNum = parseInt(item.goodsNum) - 1;
    if (goodsNum > 0) {
      nativeApi.initAjax({
        type: 'PUT',
        url: APIS.ChangeCartGoodsNum + item.id + '?goodsNum=' + goodsNum,
        callback: function (result) {
          if (result && result.code === 200) {
            var items = self.state.cartList[row].items;
            items[index].goodsNum = goodsNum;
            self.state.cartList[row].items = items;
            self.subtotal();
          }
        }
      });
    }
  },
  setGoodsNum: function (goodsNum, row, index) {
    var self = this;
    var item = self.state.cartList[row].items[index];
    if (goodsNum > 0) {
      nativeApi.initAjax({
        type: 'PUT',
        url: APIS.ChangeCartGoodsNum + item.id + '?goodsNum=' + goodsNum,
        callback: function (result) {
          if (result && result.code === 200) {
            var items = self.state.cartList[row].items;
            items[index].goodsNum = goodsNum;
            self.state.cartList[row].items = items;
            self.subtotal();
          }
        }
      });
    }
  },
  setNotActive: function () {
    var self = this;
    var list = self.state.cartList;
    self.state.isCheckAll = false;
    for (let i = 0; i < list.length; i++) {
      list[i].active = false;
      var items = list[i].items;
      for (let j = 0; j < items.length; j++) {
        var item = items[j];
        item.active = false;
      }
    }
    self.subtotal();
  },
  subtotal: function () {
    var self = this;
    var list = self.state.cartList;
    var settlement = 0;
    var settlementData = [];
    var row = 0;
    for (let i = 0; i < list.length; i++) {
      var items = list[i].items;
      var isCheckAllItem = 0;
      for (let j = 0; j < items.length; j++) {
        var item = items[j];
        if (item.active) {
          ++isCheckAllItem;
          settlement += item.point * item.goodsNum;
          settlementData.push(item.id);
        }
      }
      if (isCheckAllItem === items.length) {
        ++row;
      }
    }
    if (row === list.length) {
      self.state.isCheckAll = true;
    } else {
      self.state.isCheckAll = false;
    }
    self.state.settlement = settlement;
    self.state.settlementData = settlementData;
    self.state.settlementurl = {'settlementData': settlementData, 'settlement': settlement};
  },
  chooesGood: function (row, index) {
    var self = this;
    if (index === undefined) {
      self.state.cartList[row].active = !self.state.cartList[row].active;
      for (let j = 0; j < self.state.cartList[row].items.length; j++) {
        self.state.cartList[row].items[j].active = self.state.cartList[row].active;
      }
    } else {
      var isChooesAll = 0;
      self.state.cartList[row].items[index].active = !self.state.cartList[row].items[index].active;
      for (let j = 0; j < self.state.cartList[row].items.length; j++) {
        if (self.state.cartList[row].items[j].active) {
          ++isChooesAll;
        }
      }
      if (isChooesAll === self.state.cartList[row].items.length) {
        self.state.cartList[row].active = true;
      } else {
        self.state.cartList[row].active = false;
      }
    }
    self.subtotal();
  },
  checkAll: function () {
    var self = this;
    self.state.isCheckAll = !self.state.isCheckAll;
    for (let i = 0; i < self.state.cartList.length; i++) {
      self.state.cartList[i].active = self.state.isCheckAll;
      for (let j = 0; j < self.state.cartList[i].items.length; j++) {
        self.state.cartList[i].items[j].active = self.state.isCheckAll;
      }
    }
    self.subtotal();
  },
  getSettlement: function (str) {
    var self = this;
    if (str !== 'false') {
      var jsonData = JSON.parse(str);
      self.state.settlement = jsonData.settlement;
    }
  },
  getSettlementData: function (str) {
    var self = this;
    if (str !== 'false') {
      var jsonData = JSON.parse(str);
      self.state.settlement = jsonData.settlement;
      self.state.settlementData = jsonData.settlementData;
    }
  },
  getAddressId: function (id) {
    var self = this;
    nativeApi.initAjax({
      type: 'GET',
      url: APIS.getAddressId + '/' + id,
      callback: function (result) {
        if (result && result.code === 200) {
          self.state.address = result.data;
          self.state.addressId = result.data.id;
        } else {
          // mui.confirm('暂无地址，是否前往管理地址？', function (e) {
          //   if (e.index === 1) {
          //     window.location.href = '/we/index.html#!/address/' + self.state.paramsData;
          //   }
          // });
        }
      }
    });
  },
  settle: function () {
    var self = this;
    var str = JSON.stringify(self.state.settlementData);
    nativeApi.initAjax({
      type: 'POST',
      url: APIS.Cartsettle,
      param: {
        addressId: self.state.addressId,
        cartIds: str.substring(1, str.length - 1)
      },
      callback: function (result) {
        if (result && result.code === 200) {
          mui.confirm('您已扣除' + result.data.orderGoodsPoint + '积分', '兑换成功！', ['查看订单', '返回首页'], function (e) {
            if (e.index === 1) {
              location.href = '/mallHome/index.html';
            } else {
              location.href = '/we/index.html#!/orderList?orderStatus=-1';
            }
          }, 'div');
        } else {
          mui.alert(result.msg);
        }
      }
    });
  },
  getGoodsList: function (str) {
    var self = this;
    nativeApi.initAjax({
      type: 'GET',
      url: APIS.getGoodsList + '?ids=' + str,
      callback: function (result) {
        if (result && result.code === 200) {
          self.state.goodsList = result.data;
        } else {
          mui.alert(result.msg);
        }
      }
    });
  },
  deleCart: function () {
    var self = this;
    var list = JSON.parse(JSON.stringify(self.state.cartList));
    var settlementData = [];
    for (let i = 0; i < list.length; i++) {
      var items = list[i].items;
      for (let j = 0; j < items.length; j++) {
        var item = items[j];
        if (item.active) {
          settlementData.push(item.id);
        }
      }
    }
    if (settlementData.length <= 0) {
      mui.alert('未选中任何商品');
      return false;
    }
    mui.confirm('是否刪除？', function (e) {
      if (e.index === 1) {
        var str = JSON.stringify(settlementData);
        nativeApi.initAjax({
          type: 'POST',
          url: APIS.deleCarts,
          param: {
            ids: str.substring(1, str.length - 1)
          },
          callback: function (result) {
            if (result && result.code === 200) {
              var newList = [];
              for (let i = 0; i < list.length; i++) {
                var items = {'items': []};
                for (let j = 0; j < list[i].items.length; j++) {
                  var item = list[i].items[j];
                  if (!item.active) {
                    items.items.push(item);
                  }
                }
                if (items.items.length > 0) {
                  var value = {};
                  value.userName = list[i].userName;
                  value.id = list[i].id;
                  value.mallId = list[i].mallId;
                  value.memberId = list[i].memberId;
                  value.items = items.items;
                  value.active = false;
                  newList.push(value);
                }
              }
              self.state.cartList = newList;
              if (newList.length <= 0) {
                self.state.cartsNo = 1;
                self.getCartList();
              }
            } else {
              mui.alert(result.msg);
            }
          }
        });
      } else {
      }
    }, 'div');
  },
  settleNow: function (obj) {
    var self = this;
    nativeApi.initAjax({
      type: 'POST',
      url: APIS.settleNow + obj.id,
      param: {
        addressId: self.state.addressId,
        goodsNum: obj.num
      },
      callback: function (result) {
        if (result && result.code === 200) {
          mui.confirm('您已扣除' + result.data.orderGoodsPoint + '积分', '兑换成功！', ['查看订单', '返回首页'], function (e) {
            if (e.index === 1) {
              location.href = '/mallHome/index.html';
            } else {
              location.href = '/we/index.html#!/orderList?orderStatus=-1';
            }
          }, 'div');
        } else {
          mui.alert(result.msg);
        }
      }
    });
  },
  // 获取商品详情
  getDetail: function (id) {
    var self = this;
    nativeApi.initAjax({
      type: 'get',
      url: APIS.Goods + '/' + id,
      callback: function (result) {
        if (result && result.code === 200) {
          self.state.detail = result.data;
        } else {
          mui.alert(result.msg, function () {
            window.history.go(-1);
          });
        }
      }
    });
  },
  // 查看商品详情
  lookGoodsDetail: function (id) {
    nativeApi.initAjax({
      type: 'get',
      url: APIS.Goods + '/' + id,
      callback: function (result) {
        if (result && result.code === 200) {
          window.location.href = '../../mallHome/index.html#/goods/' + id;
        } else {
          mui.alert(result.msg, function () {
          });
        }
      }
    });
  }
};
